package com.vren.addressParse.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.vren.addressParse.modules.addressParse.ParseService;
import com.vren.addressParse.modules.addressParse.domain.address.Address;
import com.vren.addressParse.modules.addressParse.domain.dto.AddressDTO;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @ClassName:ExcelLIstener
 * @Description:
 * @Author: vren
 * @Date: 2022/6/28 14:44
 */

public class ExcelListener extends AnalysisEventListener<AddressDTO> {

    private final ParseService parseService;

    public ExcelListener(ParseService parseService) {
        this.parseService = parseService;
    }

    private List<AddressDTO> data = new LinkedList<>();

    List<Address> result = new ArrayList<>();
    List<CompletableFuture<List<Address>>> futures = new ArrayList<>();

    @Override
    public void invoke(AddressDTO t, AnalysisContext analysisContext) {
        data.add(t);
        if (data.size() >= ParseService.batchSize) {
            futures.add(parseService.parseCompletableFuture(new ArrayList<>(data), result));
            data.clear();
        }
    }

    public List<Address> getResult() {
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        return result;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        futures.add(parseService.parseCompletableFuture(new ArrayList<>(data), result));
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        super.onException(exception, context);
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        super.extra(extra, context);
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        return super.hasNext(context);
    }
}
